<template>
  <div class="allUser common-container">
    <div class="common-top">
      <span class="left">
        <el-form :inline="true" :model="formInline" size="small" class="demo-form-inline">
          <el-form-item label="搜索">
            <el-input v-model="formInline.searchVal" placeholder="搜索"></el-input>
          </el-form-item>
                    <el-form-item>
                       <el-select v-model="inviter" placeholder="请选择" @change="getData">
    <el-option
      v-for="item in inviterOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
            </el-form-item>
          <el-form-item>
                       <el-select v-model="excellentInviter" placeholder="请选择" @change="getData">
    <el-option
      v-for="item in excellentInviterOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
            </el-form-item>
          <el-form-item>
            <el-checkbox v-model="showTodayOnline">只显示今日活跃</el-checkbox>
            </el-form-item>
        </el-form>
      </span>
    </div>
    <div class="common-bot">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="ID" prop="id" align="center"></el-table-column>
        <el-table-column label="openID" prop="openId" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.wxIds.length !== 0 ? scope.row.wxIds[0].openId : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐人" align="center" width="100" v-if="hasPerm('users:user:detail')">
          <template slot-scope="scope">
            <span class="span-modify edit" @click.stop="doModify('edit',scope.row.inviteUser)"
                  v-if="scope.row.inviteUser">{{scope.row.inviteUser.name}}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名" width="150" align="center"></el-table-column>
        <el-table-column prop="avatar" label="头像" align="center" width="80">
          <template slot-scope="scope">
            <el-avatar :size="'large'" v-if="scope.row.avatar" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <!--<el-table-column prop="mobile" label="手机号" align="center"></el-table-column>-->

        <el-table-column prop="name" label="性别" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ genderFormat[scope.row.gender] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="是否启用" v-if="hasPerm('users:user:enable')" align="center" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" @change="modifyEnable(scope.row.id, scope.row.enable)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否设置为团长" align="center" v-if="hasPerm('users:user:inviterSwitch')">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.inviter"
                       @change="modifyInviterSwitch(scope.row.id, scope.row.inviter)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="是否是优秀团长" align="center" v-if="hasPerm('users:user:excellentInviterSwitch')">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.excellentInviter"
                       @change="modifyExcellentInviterSwitch(scope.row.id, scope.row.excellentInviter)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="推广人数" align="center" width="100">
          <template slot-scope="scope">
            <span class="link-type" style="cursor: pointer;color: #409EFF"
                  @click="openInviter(scope.row)">{{ scope.row.inviteCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拼团次数" align="center" width="100">
          <template slot-scope="scope">
            <span class="link-type">{{ scope.row.groupCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后拼团时间" align="center" width="100">
          <template slot-scope="scope">
            <span
              v-if="scope.row.lastGroupTime>0">{{ scope.row.lastGroupTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            <span v-else>未参与</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"
                         v-if="hasPerm('users:user:state') || hasPerm('users:user:detail') || hasPerm('users:user:del')">
          <template slot-scope="scope">
            <span class="span-modify edit" @click.stop="statisticsDialog(scope.row)"
                  v-if="hasPerm('users:user:state') && scope.row.inviter">拼团统计</span>
            <span class="span-modify edit" @click.stop="doModify('edit',scope.row)" v-if="hasPerm('users:user:detail')">详情</span>
            <span class="span-modify del" @click.stop="doModify('del',scope.row)"
                  v-if="hasPerm('users:user:del')">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="showPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="nowPage"
          :page-size="limit"
          layout="total, prev, pager, next"
          :total="totalElement"
        ></el-pagination>
      </div>
    </div>

    <el-dialog title="推广用户数据" :visible.sync="inviterDialog" class="abow_dialog">
      <el-table :data="inviteData" class="getDataTable">
        <!--<el-table-column label="序号" type="index" width="80" align="center"></el-table-column>-->
        <el-table-column label="序号" prop="" width="80" align="center">
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)"> </span>
          </template>
        </el-table-column>

        <el-table-column label="ID" prop="id" align="center"></el-table-column>
        <el-table-column label="openID" prop="openId" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.wxIds.length !== 0 ? scope.row.wxIds[0].openId : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名" width="150" align="center"></el-table-column>
        <el-table-column prop="avatar" label="头像" align="center">
          <template slot-scope="scope">
            <el-avatar :size="'large'" v-if="scope.row.avatar" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <!--<el-table-column prop="mobile" label="手机号" align="center"></el-table-column>-->

        <el-table-column prop="name" label="性别" align="center">
          <template slot-scope="scope">
            <span>{{ genderFormat[scope.row.gender] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="paginationContainer" style="margin-top: 20px;text-align: center">
        <el-pagination
          @size-change="handleSizeChange_joinGroupData"
          @current-change="handleCurrentChange_joinGroupData"
          current-page.sync="1"
          :page-size="joinGroupParams.limit"
          layout="total, prev, pager, next"
          :total="joinGroupTotal"
        ></el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="团长的拼团统计" :visible.sync="groupStatisticsDialog" class="abow_dialog">
      <div style="margin-bottom: 20px">
        <el-date-picker
          v-model="value1"
          type="week"
          @change="changePicker"
          format="yyyy 第 W 周"
          :picker-options="{firstDayOfWeek:1}"
          placeholder="选择周">
        </el-date-picker>
        <span style="margin-left: 20px"> 拼友数量:{{ memberCount }}</span>
      </div>

      <el-table :data="groupStatisticsData" class="getDataTable">
        <el-table-column prop="days" label="日期" width="150" align="center"></el-table-column>
        <el-table-column prop="total" label="参团人数" align="center"></el-table-column>
      </el-table>
      <!--<div class="paginationContainer" style="margin-top: 20px;text-align: center">-->
      <!--<el-pagination-->
      <!--@size-change="handleSizeChange_joinGroupData"-->
      <!--@current-change="handleCurrentChange_joinGroupData"-->
      <!--:current-page="1"-->
      <!--:page-sizes="[10, 20, 30, 50]"-->
      <!--:page-size="joinGroupParams.limit"-->
      <!--layout="total, sizes, prev, pager, next, jumper"-->
      <!--:total="joinGroupTotal">-->
      <!--</el-pagination>-->
      <!--</div>-->
    </el-dialog>

  </div>
</template>

<script>
  import {mapGetters} from "vuex";
  import {parseTime} from '../../utils/index'
  import {excellentInviterSwitch, inviterSwitch, userData, userDel, userEnable, userState} from '@/api/user'

  export default {
    name: "allUser",
    computed: {
      ...mapGetters(["name"]),
    },
    data() {
      return {
        showPage: false,
        inviter: null,
        excellentInviter: null,
        showTodayOnline: false,
        value1: "",
        inviterDialog: false,
        groupStatisticsDialog: false,
        groupStatisticsData: [],
        dialogType: "",
        memberCount: 0, //拼友数量
        startTime: 0, //开始时间
        endTime: 0, //结束时间
        inviteUserId: 0, //团长ID
        formInline: {
          searchVal: "",
        },
        joinGroupParams: {
          page: 0,
          limit: 10,
          inviteUserId: 0,
        },
        genderFormat: {
          male: "男",
          female: "女",
        },
        inviterOptions: [
          {
            value: 0,
            label: '全部',
          }, {
            value: 1,
            label: '团长',
          }, {
            value: 2,
            label: '非团长',
          },
        ],
        excellentInviterOptions: [
          {
            value: 0,
            label: '全部',
          }, {
            value: 1,
            label: '优秀团长',
          }, {
            value: 2,
            label: '非优秀团长',
          },
        ],
        authForm: {
          coupon: false,
          course: false,
          gold: false,
          money: false,
          qa: false,
          targetId: "",
        },
        nowSelItem: {},
        wealthTypeOptions: [],
        rechargeForm: {
          wealthType: "",
          offset: "",
          detail: "",
        },
        showDialog: false,
        tableData: [],
        inviteData: [],
        limit: 10,
        nowPage: 1,
        totalElement: 0,
        joinGroupTotal: 0,
        keyword: "",
      };
    },
    watch: {
      nowPage(val) {
        this.getData();
        this.setStateData(val);
      },
      showDialog(val) {
        if (!val) {
          this.nowSelItem = {};
          this.rechargeForm = {
            wealthType: "",
            offset: "",
            detail: "",
          };
        }
      },
      "formInline.searchVal": function (val) {
        this.getData();
      },
      limit(val) {
        this.getData();
      },
      showTodayOnline(val) {
        this.getData();
      },
    },
    methods: {
      //获取表格序号
      getIndex($index) {
        return (this.joinGroupParams.page) * this.joinGroupParams.limit + $index + 1
      },
      changePicker() {
        console.log(this.value1, "value1-88888");
        let preDate = new Date(this.value1.getTime() - 24 * 60 * 60 * 1000); //前一天
        let firstDay = parseTime(preDate, '{y}-{m}-{d} {h}:{i}:{s}');
        let firstDayTimestamp = new Date(firstDay).getTime();
        let firstDayFormat = parseTime(firstDay, '{y}-{m}-{d} {h}:{i}:{s}');
        // let year = parseTime(firstDayFormat, '{y}');
        // let month = parseTime(firstDayFormat, '{m}');
        // let day = parseTime(firstDayFormat, '{d}');
        this.startTime = firstDayTimestamp;
        this.endTime = firstDayTimestamp + 7 * 24 * 60 * 60 * 1000 - 1;
        console.log(this.startTime, this.endTime, "time-changePicker");
        this.userState();
      },
      userState() {
        userState({
          startTime: this.startTime,
          endTime: this.endTime,
          targetId: this.inviteUserId,
        })
          .then((res) => {
            if (res.code === 200) {
              this.memberCount = res.data.memberCount
              this.groupStatisticsData = res.data.counts
            }
          });
      },
      modifyEnable(id, enable) {
        userEnable({
          targetIds: [id,],
          yes: enable,
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getData();
          }
        }).catch(e => {
          this.getData();
        });
      },
      openInviter(item) {
        this.inviterDialog = true
        this.inviteUserId = item.id
        this.getPromoteUserList()
      },
      handleCurrentChange_joinGroupData(val) {
        this.joinGroupParams.page = val - 1
        this.getPromoteUserList()
      },
      handleSizeChange_joinGroupData(val) {
        this.joinGroupParams.limit = val
        this.getPromoteUserList()
      },
      //获取推广用户列表
      getPromoteUserList() {
        userData({
          limit: this.joinGroupParams.limit,
          inviteUserId: this.inviteUserId,
          page: this.joinGroupParams.page,
        })
          .then((res) => {
            if (res.code === 200) {
              this.inviteData = res.data;
              this.joinGroupTotal = res.total;
            }
          });
      },
      statisticsDialog(item) {
        this.showWeekFirstDay()
        this.groupStatisticsDialog = true
        this.inviteUserId = item.id
        this.userState();
      },

      async showCurrentWeek() {
        var date = new Date();
        var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
        var firstWeek = new Date(date.getFullYear(), date.getMonth(), 7);
        let firstDayFormat = parseTime(firstDay, '{y}-{m}-{d} {h}:{i}:{s}')
        let firstWeekFormat = parseTime(firstWeek, '{y}-{m}-{d} {h}:{i}:{s}')
        this.value1 = new Date(firstDayFormat).getTime()
        this.startTime = new Date(firstDayFormat).getTime();
        this.endTime = new Date(firstWeekFormat).getTime() + 24 * 60 * 60 * 1000 - 1
      },
      // 默认展示本周
      showWeekFirstDay() {
        var nowTemp = new Date();//当前时间
        var oneDayLong = 246060 * 1000;//一天的毫秒数
        var c_time = nowTemp.getTime();//当前时间的毫秒时间
        var c_day = nowTemp.getDay() || 7;//当前时间的星期几
        console.log(c_day, "当前时间的星期几");
        var m_time = c_time - (c_day - 1) * oneDayLong + 5 * 3600 * 24 * 1000;//当前周一的毫秒时间
        var monday = new Date(m_time);//设置周一时间对象
        console.log(monday, "设置周一时间对象");
        var mondayFormat = new Date(m_time).setHours(0, 0, 0, 0);//设置周一时间戳
        // var mondayFormat = new Date(m_time).setHours(23, 59, 59, 59);//设置周一时间戳


        this.value1 = mondayFormat
        this.startTime = mondayFormat
        this.endTime = mondayFormat + (7 * 24 * 60 * 60 * 1000 - 1000)
        console.log(this.startTime, this.endTime, "startTime.endTime mounted");
      },

      modifyInviterSwitch(id, enable) {
        inviterSwitch({
          targetId: id,
          yes: enable,
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getData();
          }
        }).catch(e => {
          this.getData();
        });
      },
      //是否设置优秀团长
      modifyExcellentInviterSwitch(id, enable) {
        excellentInviterSwitch({
          targetId: id,
          yes: enable,
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getData();
          }
        }).catch(e => {
          this.getData();
        });
      },
      setStateData(nowPage) {
        let stateData = {
          nowPage,
        };
        this.$router.replace({
          path: this.$route.path,
          query: {
            stateData: this.$base64.encode(JSON.stringify(stateData)),
          },
        });
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.limit = val;
      },
      handleCurrentChange(val) {
        this.nowPage = val;
      },
      getDetail(targetId) {
        new Promise((resolve) => {
          userApi.userMana
            .userDetail({
              targetId,
            })
            .then((res) => {
              this.authForm = {
                coupon: res.data.authority.coupon,
                course: res.data.authority.course,
                gold: res.data.authority.gold,
                money: res.data.authority.money,
                qa: res.data.authority.qa,
                targetId,
              };
              resolve();
            });
        });
      },
      async doModify(type, item) {
        if (type == "edit") {
          this.$router.push({name: "UserModify", query: {type, id: item.id}});
        } else if (type == "del") {
          this.$confirm("确认此操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            userDel({
              targetIds: [item.id],
            })
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("操作成功");
                  this.getData();
                }
              });
          });
        } else if (type == "recharge") {
          this.nowSelItem = item;
          this.showDialog = true;
          this.dialogType = "recharge";
        } else if (type == "auth") {
          this.nowSelItem = item;
          await this.getDetail(item.id);
          this.dialogType = "auth";
          this.showDialog = true;
        }
      },
      toModify(type) {
        this.$router.push({name: "UserModify", query: {type, id: item.id}});
      },
      getData() {
        userData({
          limit: this.limit,
          inviter: this.inviter,
          excellentInviter: this.excellentInviter,
          page: this.nowPage - 1,
          keyword: this.formInline.searchVal,
          showTodayOnline: this.showTodayOnline
        })
          .then((res) => {
            if (res.code === 200) {
              this.tableData = res.data;
              this.totalElement = res.total;
              this.showPage = true;
            }
          });
      },
    },
    mounted() {
      this.getData();
      // this.showCurrentWeek()
      this.showWeekFirstDay()
    },
  };
</script>

<style lang="scss" scoped>
  .auth-form-item {
    display: inline-block;
    width: 50%;
  }
</style>
